package com.lalosoft.gastostarjetaweb.util;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;


public class AESEncrypt {

	private final String ALGORITMO = "AES";//algoritmo (si cambia la imprementacion tambien)
	private final int LONGITUD = 128;//longitud de la llave ()
	private final String CODIFICACION = "UTF-8";//como se convertira a byte, esto sera mas adelante
	private final String CIPHER_TRANSFORMATION = "AES/CBC/PKCS5Padding";
	private byte[] parameterSpecification  = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; //16 random bytes
	
	private String key;
	
	public AESEncrypt() throws Exception{
		generaKey();
	}
	
	public void generaKey() throws Exception {
		KeyGenerator kgen = KeyGenerator.getInstance(ALGORITMO);
		kgen.init(LONGITUD);
		SecretKey skey = kgen.generateKey(); 
		key = HexToString(skey.getEncoded());
	}

	public String encripta(String cadena) throws Exception{  
		  byte[] raw = StringToHex(key);
		  SecretKeySpec skeySpec = new SecretKeySpec(raw, ALGORITMO);
		  Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION);
		  IvParameterSpec ivspec = new IvParameterSpec(parameterSpecification);
		  cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivspec);
		  byte[] encrypted = cipher.doFinal(cadena.getBytes(CODIFICACION));
		  String encriptado = HexToString(encrypted);
		  return encriptado;
	}
	
	private String HexToString(byte[] arregloEncriptado) {
		String textoEncriptado = "";
		for (int i = 0; i < arregloEncriptado.length; i++) {
			int aux = arregloEncriptado[i] & 0xff;
			if (aux < 16) {
				textoEncriptado = textoEncriptado.concat("0");
			}
			textoEncriptado = textoEncriptado.concat(Integer.toHexString(aux));
		}
		return textoEncriptado;
	}

	private byte[] StringToHex(String encriptado) {
		byte[] enBytes = new byte[encriptado.length() / 2];
		for (int i = 0; i < enBytes.length; i++) {
			int index = i * 2;
			String aux = encriptado.substring(index, index + 2);
			int v = Integer.parseInt(aux, 16);
			enBytes[i] = (byte) v;
		}
		return enBytes;
	}
	
	public String desencriptar(String encriptado) throws Exception{
		 byte[] raw = StringToHex(key);
		 SecretKeySpec skeySpec = new SecretKeySpec(raw, ALGORITMO);
		 Cipher cipher = Cipher.getInstance(ALGORITMO);  
		 IvParameterSpec ivspec = new IvParameterSpec(parameterSpecification);
		 cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivspec);
		 byte[] original = cipher.doFinal(StringToHex(encriptado));
		 String originalString = new String(original);
		 return originalString;
	}

	public String getKey(){
		return key;
	}
}
